const express = require('express');
const cors = require('cors');
const config = require('./config.js');
const expiresJWT = require('express-jwt');
// 导入验证规则的包
const joi = require('joi');
const app = express();
// 导入数据库
const database = require('./router/database.js');
app.use(database);
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
// 封装状态中间件
app.use((req,res,next) => {
    res._text = (err,status = 1) => {
        res.send({
            code: err === "身份认证失败" ? 0 : !status ? 200 : 400, 
            status,
            message: err instanceof Error ? err.message : err
        });
    };
    next();
});
// 解析token秘钥中间件
app.use(expiresJWT({ secret: config.jwtSecretKet,algorithms: ['HS256'] }).unless({ path: [/^\/api/] }));
// TODO: 压入路由 登录模块
const userRouter = require('./router/user.js');
app.use('/api',userRouter);
// TODO: 用户信息模块
const userinForouter = require('./router/userinfo.js');
app.use('/my',userinForouter);
// TODO: 导入文章分类的路由模块
const artcateRouter = require('./router/artcate.js');
app.use('/my/article',artcateRouter);
// TODO: 导入文章的路由模块
const articleRouter = require('./router/article.js');
app.use('/my/article',articleRouter);
// 定义验证错误级别的中间件
app.use((err,req,res,next) => {
    // 验证失败导致的错误
    if(err instanceof joi.ValidationError)return res._text(err);
    // 身份认证失败后的错误
    if(err.name === 'UnauthorizedError')return res._text('身份认证失败');
    // 未知的错误
    return res._text(err);
});
app.listen('8020',() => {
    console.log('服务器启动成功 http://127.0.0.1:8020');
});